package com.boarsoft.boar.deploy.event;

import java.util.HashMap;
import java.util.Map;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.app.AppInstBiz;
import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.boar.deploy.plan.bean.BuildRequest;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.Util;
import com.boarsoft.web.websocket.WebsocketEndpoint;
import com.boarsoft.web.websocket.WebsocketMessage;

/**
 * 
 * @author Mac_J
 *
 */
@Component("deployEventSvc")
public class DeployEventSvcImpl implements DeployEventSvc {
	private static final Logger log = LoggerFactory.getLogger(DeployEventSvcImpl.class);

	@Autowired
	protected AppInstBiz appInstBiz;

	@Override
	public void on(DeployEvent e) throws Exception {
		log.info("Received deploy event: {}", e);
		String instId = e.getInstId();
		if (Util.strIsEmpty(instId)) {
			String addr = e.getAddr();
			String[] a = addr.split(":");
			AppInst inst = appInstBiz.find(a[0], Integer.parseInt(a[1]));
			instId = inst.getId();
		}
		// 此消息是由负责部署或监控此应用的服务发送的
		appInstBiz.status(instId, e.getStatus());
		//
		String reqId = e.getRequestId();
		if (Util.strIsEmpty(reqId)) {
			return;
		}
		Cache cache = ActionContext.getCache();
		BuildRequest po = (BuildRequest) cache.get("deploy", reqId);
		// String[] a = key.split("/");
		// String sessionId = a[0];
		// String taskId = a[1];
		// // String env = a[2];
		String wssid = po.getWssid();
		Session session = WebsocketEndpoint.getSession(wssid);
		if (session == null) {
			log.warn("Websocket session expired, ignore deploy event {}", e);
			return;
		}
		//
		Map<String, Object> rm = new HashMap<String, Object>();
		// rm.put("addr", addr);
		// rm.put("appCode", app.getCode());
		rm.put("instId", instId);
		rm.put("status", e.getStatus());
		//
		WebsocketMessage mw = new WebsocketMessage();
		mw.setGroup("deploy");
		mw.setCode("event");
		mw.setData(rm);
		WebsocketEndpoint.send(mw, wssid);
	}
}